import sys
import time
from configparser import ConfigParser
from Core import request_driver as webdriver
import config as conf
import requests
import json
from tqdm import tqdm


# 获取数据结果检查
def result_check(status):
    if status['status'] == "error":
        print(status)
        sys.exit(0)


# 获取测试信息
def get_exam():
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/regular/index?lang=zh&utcoffset=-28800&exam_year=2023&sub_type=business&page=1&limit=16'
    obj = MyReq.http_get_by_json(url)
    result_check(obj)
    return obj


# 获取考试试卷
def get_exam_paper(exam_id):
    unix_time = str(int(time.time()))
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/start?lang=zh&utcoffset=-28800&examId=' \
          + exam_id + '&type=normal&start_time=' + unix_time
    # print('GET', url)
    obj = MyReq.http_get_by_json(url)
    result_check(obj)
    return obj


# 获取试卷答案
def get_exam_result(result_id):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/' \
          'resultDetail?lang=zh&utcoffset=-28800&type=normal&resultId=' + result_id
    obj = MyReq.http_get_by_json(url)
    result_check(obj)
    return obj


# 发送答案参数
def post_exam(data):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/finish?lang=zh&utcoffset=-28800'
    obj = MyReq.http_post_by_json(url, data)
    result_check(obj)
    return obj


# 获取答题结果
def get_result(exam_id):
    url = 'https://xingshui.chinatax.gov.cn/NewSoke/exam/home/v1/exam/detail?lang=zh&utcoffset=-28800&from=exam&examId=' + exam_id
    obj = MyReq.http_get_by_json(url)
    result_check(obj)
    return obj


# 远程过程认证
def auth():
    import requests
    url = 'https://www.my-aihome.cn/2021dingqiceshi-rs.json'
    response = requests.get(url, verify=False).json()
    if response['flag'] == 'True':
        return True
    else:
        sys.exit(0)


def get_user_info(username):
    config = ConfigParser()
    path = r'userinfo.ini'
    config.read(path)
    return config[username]['answertime'], config[username]['mobile'], config[username]['Authorization']


def send_sms_message(mobile, exam_title, start_time, end_time, total_score):
    url = "http://sms-api.luosimao.com/v1/send.json"
    send_data = {
        "mobile": mobile,
        "message": "你参加的<{}>,开始时间:{},结束时间:{},分数:{}。【两测考试】".format(exam_title, start_time, end_time, total_score)
    }
    resp = requests.post(url=url, auth=("api", "key-ae7d4ecf14aa2648d7f7b7d2eb353bce"), data=send_data, timeout=3,
                         verify=False)
    return resp.json()


if __name__ == '__main__':
    MyReq = webdriver.DriverRequests(True, False)
    # if len(sys.argv) > 1:
    #     user = sys.argv[1]
    # else:
    #     user = input('请输入用户:')
    # answertime, mobile, conf.Headers['Authorization'] = get_user_info(user)
    conf.Headers['Authorization'] = input('Please Input Token:')
    answertime = input('请输入答题时间(秒):')
    # 程序开始执行
    start_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    # 获取两测考试相关信息
    print('开始获取试题信息.....', end=' ')
    exam_res = get_exam()
    print(exam_res['message'])
    # print(exam_res)



    exam_title = exam_res['data']['list'][0]['title']
    exam_uuid = exam_res['data']['list'][0]['uuid']
    print('开始作答:', exam_title, exam_uuid)

    # 获取试题
    print('获取题目....', end=' ')
    exam_paper_res = get_exam_paper(exam_uuid)
    print(exam_paper_res['message'])

    result_id = exam_paper_res['data']['resultId']

    # 获取试题答案
    print('查询答案....', end=' ')
    exam_answer_res = get_exam_result(result_id)['data']
    print('完毕!!!')
    # print(exam_answer_res)
    # print('\n')

    # 组成试题答案，做为参数发送给服务器
    my_answer = {}
    my_answer['usedTime'] = answertime
    my_answer['resultId'] = result_id
    my_answer['examId'] = exam_uuid
    my_answer['buildId'] = exam_paper_res['data']['buildId']
    my_answer['submitType'] = 'compel'
    my_answer['type'] = 'normal'

    exam_answer_items = exam_answer_res['items']
    for uuid, item in exam_answer_items.items():
        if item['type'] == 'material':
            exam_answer_items_subs = item['subs']
            for sub_uuid, sub_item in exam_answer_items_subs.items():
                for sub_answer_index, sub_answer_item in enumerate(sub_item['answer']):
                    my_answer['data[' + sub_uuid + '][' + str(sub_answer_index) + ']'] = sub_answer_item
        else:
            for answer_index, answer_item in enumerate(item['answer']):
                my_answer['data[' + uuid + '][' + str(answer_index) + ']'] = answer_item

    # # 最后五题全部选第一项
    # last5 = list(my_answer.keys())[-5:]
    # # print(last5)
    # for item_last5 in last5:
    #     my_answer[item_last5] = '0'
    # print(my_answer)

    for i in tqdm(range(int(answertime)), desc='正在作答'):
        time.sleep(1)

    # 提交答案
    res = post_exam(my_answer)
    print('\n提交数据....', res['message'])
    # 获取测试结果
    print('获取结果....', end=' ')
    result = get_result(exam_uuid)
    print(result['message'])
    print(result['data']['examUser']['dept_names'], '-----', result['data']['examUser']['user_name'])
    print('试卷名称', result['data']['info']['title'], '分数', result['data']['info']['total_score'])

    end_time = time.strftime('%H:%M:%S', time.localtime(time.time()))
    # send_sms_message(mobile, exam_title, start_time, end_time, result['data']['info']['total_score'])